package com.hjl.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 *
 * @author Lenovo
 * @version 1.0
 * @date 2021/10/8 11:26
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    /**
     * 不进行过滤的
     */
    public static final String PATH1 = "/user/login";
    public static final String PATH2 = "/css/";
    public static final String PATH3 = "/js/";
    public static final String PATH4 = "/checkCode/";
    public static final String PATH5 = "/loginForm.jsp";

    @Override
    public void destroy() {
    }

    /**
     * 过滤非登录页面
     *
     * @author Lenovo
     * @date 2021/10/8 20:22
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //强制转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取路径
        String requestUri = request.getRequestURI();
        //如果是登录相关资源，放行（注意排除css js 图片 验证码等资源）
        //待解决：直接访问servlet，有几张图放行失败
        if (requestUri.contains(PATH1) || requestUri.contains(PATH2) || requestUri.contains(PATH3)
                || requestUri.contains(PATH4) || requestUri.contains(PATH5)) {
            chain.doFilter(req, resp);
        } else {
            //不包含，验证是否登录
            Object user = request.getSession().getAttribute("user");
            if (user != null) {
                chain.doFilter(req, resp);
            } else {
                response.sendRedirect(request.getContextPath() + "/loginForm.jsp");
            }
        }
    }

    /**
     * 初始化
     *
     * @author Lenovo
     * @date 2021/10/8 20:23
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}
